#pragma once

#include "hash.h"

template<typename K>
struct HashFunc
{
	size_t operator()(const K& key)
	{
		return (size_t)key;
	}
};

template<>
struct HashFunc<string>
{
	size_t operator()(const string& s)
	{
		size_t ans = 0;
		for (auto& e : s)
		{
			ans *= 131;
			ans += e;
		}
		return ans;
	}
};

namespace byh
{
	template<typename K, typename V, typename Hash = HashFunc<K>>
	class unordered_map
	{
		struct KeyOfMap
		{
			const K& operator()(const pair<K, V>& kv)
			{
				return kv.first;
			}
		};

	public:
		using iterator = typename hash_bucket::HashTable<K, pair<const K, V>, KeyOfMap, Hash>::iterator;
		using const_iterator = typename hash_bucket::HashTable<K, pair<const K, V>, KeyOfMap, Hash>::const_iterator;

		pair<iterator, bool> insert(const pair<K, V>& kv)
		{
			return _hash_table.insert(kv);
		}

		V& operator[](const K& key)
		{
			pair<iterator, bool> res = this->insert(make_pair(key, V()));
			return res.first->second;
		}

		iterator begin()
		{
			return _hash_table.begin();
		}

		iterator end()
		{
			return _hash_table.end();
		}

		const_iterator begin() const
		{
			return _hash_table.begin();
		}

		const_iterator end() const
		{
			return _hash_table.end();
		}

	private:
		hash_bucket::HashTable<K, pair<const K, V>, KeyOfMap, Hash> _hash_table;
	};

	void Test_Map()
	{
		unordered_map<int, int> m;
		m.insert({ 2, 1 });
		m.insert({ 1, 1 });
		m.insert({ 3, 1 });
		m.insert({ 6, 1 });
		m.insert({ 8, 1 });
		m.insert({ 7, 1 });

		unordered_map<int, int>::iterator it = m.begin();
		while (it != m.end())
		{
			cout << it->first << " " << it->second << endl;
			++it;
		}

		//vector<string> v = { "apple", "banana", "watermelon", "apple", "orange", "banana", "apple" };
		//unordered_map<string, int> m;
		//for (auto& e : v) m[e] ++;
		//for (auto& e : m)
		//{
		//	cout << e.first << " " << e.second << endl;
		//}
	}
}